package com.ziyueyuwen.xiniao.spi.impl;

import com.alibaba.fastjson.JSON;
import com.ziyueyuwen.xiniao.bean.homework.AnswerData;
import com.ziyueyuwen.xiniao.bean.homework.ItemData;
import com.ziyueyuwen.xiniao.bean.homework.QuestionInfo;
import com.ziyueyuwen.xiniao.spi.QuestionTypeService;
import com.ziyueyuwen.xiniao.util.QuestionUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import static com.ziyueyuwen.xiniao.enums.QuestionTypeEnum.SUBJECTIVE;

/**
 * @author jun 2018/12/18.
 */
public class SubjectiveImpl implements QuestionTypeService {

    @Override
    public void saveAnswer(String answerData, Integer questionNum, QuestionInfo questionInfo, List<AnswerData> answerDataList) {
        if (questionInfo.getQuestionType() == SUBJECTIVE) {
            List<String> dataList = JSON.parseArray(answerData, String.class);
            AnswerData answerDataBean = new AnswerData();
            answerDataBean.setTotalScore(getTotalScore(questionInfo.getScoreMap()));
            answerDataBean.setQuestionType(SUBJECTIVE);
            answerDataBean.setSubjectiveAnswerList(getSubjectiveAnswerList(dataList));
            answerDataBean.setCorrectScore(0);
            if (answerDataList.size() < questionNum) {
                answerDataList.add(answerDataBean);
            } else {
                answerDataList.set(questionNum - 1, answerDataBean);
            }
        }
    }

    /**
     * 获取小题的分数
     *
     * @param scoreMap TreeMap<String, Integer>
     * @return Integer
     */
    private Integer getTotalScore(TreeMap<String, Integer> scoreMap) {
        int totalScore = 0;
        for (int i : scoreMap.values()) {
            totalScore = Math.max(totalScore, i);
        }
        return totalScore;
    }

    /**
     * 获取主观题答案
     *
     * @param dataList List<String>
     * @return List<ItemData>
     */
    private List<ItemData> getSubjectiveAnswerList(List<String> dataList) {
        List<ItemData> itemDataList = new ArrayList<>();
        for (String s : dataList) {
            String str = s.trim();
            ItemData itemData = new ItemData();
            itemData.setItemType(QuestionUtil.getItemType(str));
            itemData.setItemValue(str);
            itemDataList.add(itemData);
        }
        return itemDataList;
    }

}
